<template>
    <div class="mod-config">
        <!--  头部：新增，批量删除    -->
        <div>
            <el-select v-model="value" placeholder="请选择" style="margin-right: 20px" @change="handleChange">
                <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                </el-option>
            </el-select>
            <!--    新增按钮      -->
            <el-button type="primary" icon="el-icon-circle-plus-outline" @click="addPermissions">分配权限</el-button>
            <!--    新增按钮      -->
            <el-form :inline="true" style="float:right">
                <el-form-item>
                    <el-button icon="el-icon-search" type="primary" circle @click="search"></el-button>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="searchName" placeholder="搜索权限名称如：注册用户" size="medium" class="input"
                              clearable="clearable"></el-input>
                </el-form-item>
            </el-form>
        </div>
        <el-divider></el-divider>
        <!--   主体：表格（基本信息，修改，删除）   -->
        <div class="table">
            <el-table :data="tableData" border style="width: 100%" v-loading="dataListLoading">
                <el-table-column type="index" header-align="center" align="center" width="100" label="序号">
                    <template #default="scope">
                        <span>{{ (currentPage - 1) * pageSize + scope.$index + 1 }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="名称" width="230" align="center"></el-table-column>
                <el-table-column prop="code" label="代码" width="230" align="center"></el-table-column>
                <el-table-column prop="createTime" label="创建日期" width="230" align="center"></el-table-column>
                <el-table-column prop="modifiedTime" label="修改日期" width="230" align="center"></el-table-column>
                <el-table-column fixed="right" label="操作" width="200" align="center">
                    <template slot-scope="scope">
                        <el-button size="small" icon="el-icon-turn-off" type="danger" @click="deleteAcc(scope.row.id)">
                            取消关联
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    align="left"
                    @current-change="changePage"
                    background
                    layout="total, prev, pager, next"
                    :page-size="pageSize"
                    :current-page="currentPage"
                    :total="total">
            </el-pagination>
            <el-dialog title="关联权限数据" :visible.sync="editFormVisibleForAddPermissions" :show-close="isClose"
                       :close-on-click-modal="isClose" center>
                <el-divider><i class="el-icon-setting"></i></el-divider>
                <el-table :data="allData" border style="width: 100%" @selection-change="selectionChangeHandle" >
                    <el-table-column type="selection" header-align="center" align="center" width="50">
                    </el-table-column>
                    <el-table-column prop="name" label="名称" width="300" align="center"></el-table-column>
                    <el-table-column prop="code" label="代码" width="300" align="center"></el-table-column>
                </el-table>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="editFormVisibleForAddPermissions=false">取 消</el-button>
                    <el-button type="primary" @click="commitPermissions">确 定</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>
<script>
import dayjs from "dayjs";
const cityOptions = [{id:1,name:'上海'}, {id:2,name:'北京'}, {id:3,name:'广州'}, {id:4,name:'深圳'}, {id:5,name:'南京'}];
export default {
    data() {
        return {
            //是否为搜索状态
            isSearch:false,
            // 当前页
            currentPage: this.$router.currentRoute.query.page ? parseInt(this.$router.currentRoute.query.page) : 1,
            // 一共多少页
            pageSize: 10,
            // 一共多少条
            total: 10,
            // 加载
            dataListLoading: false,
            //表格数据
            tableData: [],
            //下拉框数据
            options: [],
            // 下拉框选中值
            value: '',
            // 搜索
            searchName: '',
            //是否主动开启
            isClose: false,
            // 弹窗
            editFormVisibleForAddPermissions: false,
            //所有权限数据
            allData: [],
            //选中的id
            checkList: []
        }
    },
    mounted() {
        this.isSearch = false;
        this.loadOptions();
    },
    methods: {
        dayjs,
        rolePermission(e,message){
            if(e.name === '' || e.name === null){
                e.name = message;
            }
            if(e.code === '' || e.code === null){
                e.code = message;
            }
            if(e.createTime === '' || e.createTime === null){
                e.createTime = message;
            }else {
                e.createTime = dayjs(e.createTime).format('YYYY-MM-DD HH:mm:ss');
            }
            if(e.modifiedTime === '' || e.modifiedTime === null){
                e.modifiedTime = message;
            }else {
                e.modifiedTime = dayjs(e.modifiedTime).format('YYYY-MM-DD HH:mm:ss');
            }
        },
        reSearch() {
            let that = this;
            this.currentPage=1;
            that.$http('/role/search/permissionList','POST',{
                name: that.searchName,
                roleId: that.value,
                pageNum: that.currentPage
            },(resp)=>{
                if(resp.data.code === 20000){
                    let data = resp.data.data;
                    that.tableData = data.list;
                    if(data.list.length>0){
                        let message = '暂无'
                        for (let e of that.tableData){
                            this.rolePermission(e,message);
                        }
                        that.currentPage = resp.data.data.currentPage;
                        that.pageSize = resp.data.data.pageSize;
                        that.total = resp.data.data.total;
                    }else {
                        that.$message({
                            type: 'info',
                            message: '未搜索到结果，请重试！'
                        });
                    }
                }
            })
        },
        //根据权限名称进行搜索
        search(){
            let that = this;
            this.isSearch = true;
            if (that.searchName === '') {
                that.$message({
                    type: 'error',
                    message: '请先填写需要搜索的名称'
                });
                this.isSearch = false;
            }
            that.$http('/role/search/permissionList','POST',{
                name: that.searchName,
                roleId: that.value,
                pageNum: that.currentPage
            },(resp)=>{
                if(resp.data.code === 20000){
                    let data = resp.data.data;
                    that.tableData = data.list;
                    if(data.list.length>0){
                        let message = '暂无'
                        for (let e of that.tableData){
                            this.rolePermission(e,message);
                        }
                        that.currentPage = resp.data.data.currentPage;
                        that.pageSize = resp.data.data.pageSize;
                        that.total = resp.data.data.total;
                    }else {
                       this.reSearch();
                    }
                }
            })
        },
        //取消关联
        deleteAcc(id){
            console.log("id:"+id)
            let that = this;
            that.$confirm('此操作将取消关联, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                that.$http('/role/delete','DELETE',{
                    permissionId: id,
                    roleId: this.value
                },(resp)=>{
                    let data = resp.data;
                    if (data.code === 20000) {
                        that.$message({
                            message: '取消关联成功',
                            type: 'success'
                        });
                        that.loadRolePermissionData()
                    }
                })
            }).catch(() => {

            })

        },
        //获取批量操作的id
        selectionChangeHandle(ids) {
            this.checkList = ids;
            console.log(this.checkList)
        },
        //加载权限数据
        loadPermisssions(){
            let that = this;
            let form = {
                id:0
            };
            form.id = this.value;
            that.$http('/permission/allList','POST',form,(resp)=>{
                let data = resp.data;
                if (data.code === 20000) {
                    this.allData = data.data;
                }
            })
        },
        //提交选择的权限数据
        commitPermissions(){
            let that = this;
            if (this.checkList.length > 0) {
                let form = {
                    roleId:0,
                    permissionIds:[]
                };
                form.roleId = this.value;
                for (let i = 0; i < this.checkList.length; i++) {
                    form.permissionIds.push(this.checkList[i].id);
                }
                that.$http('/role/addPermissions','POST',form,(resp)=>{
                    let data = resp.data;
                    if (data.code === 20000) {
                        that.$message({
                            message: '添加成功',
                            type: 'success'
                        });
                        that.editFormVisibleForAddPermissions = false;
                        that.loadRolePermissionData();
                    }
                  })
            }
        },
        //关联权限弹框
        addPermissions(){
            this.loadPermisssions();
            this.editFormVisibleForAddPermissions = true;
        },
        //加载角色数据
        loadOptions() {
            let that = this;
            that.$http('/role/list', 'GET', null, (resp) => {
                let data = resp.data;
                if (data.code === 20000) {
                    let roles = data.roles;
                    if (roles.length > 0) {
                        for (let i = 0; i < roles.length; i++) {
                            let obj = {
                                value: roles[i].id,
                                label: roles[i].name
                            }
                            that.options.push(obj);
                        }
                        this.value = that.options[0].value;
                        that.loadRolePermissionData();
                        this.loadPermisssions();
                    }
                }
            })
        },
        //加载权限角色数据
        loadRolePermissionData() {
            this.dataListLoading = true;
            let that = this;
            that.$http('/role/permissions', 'POST', {
                roleId: that.value,
                page: that.currentPage
            }, (resp) => {
                if (resp.data.code === 20000) {
                    let data = resp.data.data;
                    that.tableData = data.list;
                    if (data.list.length <= 0) {
                        this.currentPage = 1;
                        this.loadData()
                    } else {
                        let message = '暂无'
                        for (let e of that.tableData){
                            this.rolePermission(e,message);
                        }
                        that.currentPage = resp.data.data.currentPage;
                        that.pageSize = resp.data.data.pageSize;
                        that.total = resp.data.data.total;
                        this.dataListLoading = false;
                    }
                }
            })
        },
        loadData(){
            let that = this;
            that.$http('/role/permissions', 'POST', {
                roleId: that.value,
                page: that.currentPage
            }, (resp) => {
                if (resp.data.code === 20000) {
                    let data = resp.data.data;
                    that.tableData = data.list;
                    if (data.list.length <= 0) {
                        this.currentPage = 1;
                    } else {
                        let message = '暂无'
                        for (let e of that.tableData){
                            this.rolePermission(e,message)
                        }
                    }
                    that.currentPage = resp.data.data.currentPage;
                    that.pageSize = resp.data.data.pageSize;
                    that.total = resp.data.data.total;
                    this.dataListLoading = false;
                }
            })
        },
        handleChange() {
            this.loadRolePermissionData()
            this.loadPermisssions()
        },
        // 切换分页
        changePage(page) {
            this.currentPage = page;
            if(this.isSearch){
                this.search();
            }else{
                this.loadRolePermissionData();
            }
        }
    }
}
</script>
<style lang="less">
.table {
  margin-top: 20px;
}
</style>